const apiAuditCmpt = Vue.component('api-audit-cmpt', {
    template: '<div>\n' +
        '    <el-dialog\n' +
        '        title="API call detailed log" :visible.sync="apiAudit" style="z-index: 3000" width="1165px" top="8vh">\n' +
        '      <div style="padding-top: 20px">\n' +
        '        <div>\n' +
        '          <el-table\n' +
        '              ref="filterTable"\n' +
        '              :data="apiAuditRecode"\n' +
        '              style="width: 100%">\n' +
        '            <el-table-column\n' +
        '                prop="idLog"\n' +
        '                label="ID"\n' +
        '                width="290">\n' +
        '            </el-table-column>\n' +
        '            <el-table-column\n' +
        '                prop="name"\n' +
        '                label="Name"\n' +
        '                width="200">\n' +
        '            </el-table-column>\n' +
        '            <el-table-column\n' +
        '                label="Request date"\n' +
        '                sortable\n' +
        '                width="180"\n' +
        '                column-key="date"\n' +
        '                prop="requestTime">\n' +
        '            </el-table-column>\n' +
        '            <el-table-column\n' +
        '                label="Response date"\n' +
        '                sortable\n' +
        '                width="180"\n' +
        '                column-key="date"\n' +
        '                prop="responseTime">\n' +
        '            </el-table-column>\n' +
        '            <el-table-column\n' +
        '                prop="sourceAddr"\n' +
        '                label="Origin"\n' +
        '                width="180">\n' +
        '            </el-table-column>\n' +
        '            <el-table-column prop="status" label="Status" width="100"\n' +
        '                             :filters="[{ text: \'正常\', value: \'正常\' }, { text: \'异常\', value: \'异常\' }]"\n' +
        '                             :filter-method="filterTag" filter-placement="bottom-end">\n' +
        '              <template slot-scope="scope">\n' +
        '                <el-tag style="cursor: pointer" :type="scope.row.status === \'异常\' ? \'danger\' : \'success\'"\n' +
        '                        @click="show(scope.row)" disable-transitions>\n' +
        '                  {{ scope.row.status }}\n' +
        '                </el-tag>\n' +
        '              </template>\n' +
        '            </el-table-column>\n' +
        '          </el-table>\n' +
        '          <div style="text-align: right;margin-top: 15px">\n' +
        '            <el-pagination background layout="total, prev, pager, next" @current-change="handleCurrentChange"\n' +
        '                           :current-page="currentPage" :page-size="pageSize" :total="logTotal"></el-pagination>\n' +
        '          </div>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '    <el-dialog\n' +
        '        title="链路详情" :visible.sync="auditLog" width="900px" top="20vh" :modal="false">\n' +
        '      <div style="padding-top: 20px">\n' +
        '        <div style="display: flex;align-items: center;justify-content: space-around;flex-wrap: nowrap">\n' +
        '          <div @click="detailNode(0)" style="display: flex;flex-direction: column;align-items: center">\n' +
        '            <i :class="icons[0].info" style="display: inline-block;width: 30px;height: 30px;font-size: 30px"></i>\n' +
        '            <span style="display: inline-block;min-width: 70px;text-align: center">\n' +
        '                进入\n' +
        '              </span>\n' +
        '          </div>\n' +
        '          <i :class="icons[0].line_info" style="width: 100%"></i>\n' +
        '\n' +
        '          <div @click="detailNode(1)" v-if="icons[1].dis"\n' +
        '               style="display: flex;flex-direction: column;align-items: center">\n' +
        '            <i :class="icons[1].info" style="display: inline-block;width: 30px;height: 30px;font-size: 30px"></i>\n' +
        '            <span style="display: inline-block;min-width: 70px;text-align: center">\n' +
        '                鉴权\n' +
        '              </span>\n' +
        '          </div>\n' +
        '          <i v-if="icons[1].dis" style="width: 100%" :class="icons[1].line_info"></i>\n' +
        '\n' +
        '          <div @click="detailNode(4)" v-if="icons[4].dis"\n' +
        '               style="display: flex;flex-direction: column;align-items: center">\n' +
        '            <i :class="icons[4].info"\n' +
        '               style="display: inline-block;width: 30px;height: 30px;font-size: 30px"></i>\n' +
        '            <span style="display: inline-block;min-width: 70px;text-align: center">\n' +
        '                限流\n' +
        '              </span>\n' +
        '          </div>\n' +
        '          <i v-if="icons[4].dis" style="width: 100%" :class="icons[4].line_info"></i>\n' +
        '\n' +
        '          <div @click="detailNode(2)" v-if="icons[2].dis"\n' +
        '               style="display: flex;flex-direction: column;align-items: center">\n' +
        '            <i :class="icons[2].info"\n' +
        '               style="display: inline-block;width: 30px;height: 30px;font-size: 30px"></i>\n' +
        '            <span style="display: inline-block;min-width: 70px;text-align: center">\n' +
        '                路由\n' +
        '              </span>\n' +
        '          </div>\n' +
        '          <i v-if="icons[2].dis" style="width: 100%" :class="icons[2].line_info"></i>\n' +
        '\n' +
        '          <div @click="detailNode(3)" v-if="icons[3].dis"\n' +
        '               style="display: flex;flex-direction: column;align-items: center">\n' +
        '            <i :class="icons[3].info" style="display: inline-block;width: 30px;height: 30px;font-size: 30px"></i>\n' +
        '            <span style="display: inline-block;min-width: 70px;text-align: center">\n' +
        '                结束\n' +
        '            </span>\n' +
        '          </div>\n' +
        '        </div>\n' +
        '\n' +
        '        <div style="margin-top: 50px;text-align: left">\n' +
        '          节点详情：<br>\n' +
        '          <div v-if="entry_node">\n' +
        '            <div v-for="(item,index) in processField[0]" :key="index">\n' +
        '              <div @click="showDetail(item)"\n' +
        '                   style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 85%;margin: 10px auto 0;">\n' +
        '                {{ item }}\n' +
        '              </div>\n' +
        '            </div>\n' +
        '          </div>\n' +
        '          <div v-if="authorize_node">\n' +
        '            <div v-for="(item,index) in processField[1]" :key="index">\n' +
        '              <div @click="showDetail(item)"\n' +
        '                   style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 85%;margin: 10px auto 0;">\n' +
        '                {{ item }}\n' +
        '              </div>\n' +
        '            </div>\n' +
        '          </div>\n' +
        '          <div v-if="routing_node">\n' +
        '            <div v-for="(item,index) in processField[2]" :key="index">\n' +
        '              <div @click="showDetail(item)"\n' +
        '                   style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 85%;margin: 10px auto 0;">\n' +
        '                {{ item }}\n' +
        '              </div>\n' +
        '            </div>\n' +
        '          </div>\n' +
        '\n' +
        '          <div v-if="end_node">\n' +
        '            <div v-for="(item,index) in processField[3]" :key="index">\n' +
        '              <div @click="showDetail(item)"\n' +
        '                   style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 85%;margin: 10px auto 0;">\n' +
        '                {{ item }}\n' +
        '              </div>\n' +
        '            </div>\n' +
        '          </div>\n' +
        '\n' +
        '          <div v-if="limiting_node">\n' +
        '            <div v-for="(item,index) in processField[4]" :key="index">\n' +
        '              <div @click="showDetail(item)"\n' +
        '                   style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 85%;margin: 10px auto 0;">\n' +
        '                {{ item }}\n' +
        '              </div>\n' +
        '            </div>\n' +
        '          </div>\n' +
        '        </div>\n' +
        '      </div>\n' +
        '      <span slot="footer" class="dialog-footer">\n' +
        '            <el-button type="primary" @click="out()">关闭</el-button>\n' +
        '          </span>\n' +
        '    </el-dialog>\n' +
        '\n' +
        '    <el-dialog\n' +
        '        title="详情日志" :visible.sync="details" width="500px" top="20vh" :modal="false">\n' +
        '      <div>\n' +
        '        <el-input readonly v-model="node_detail" rows="15" type="textarea"/>\n' +
        '      </div>\n' +
        '    </el-dialog>\n' +
        '  </div>\n' +
        '      </div>\n' +
        '      <span slot="footer" class="dialog-footer">\n' +
        '    <el-button type="primary" @click="apiAudit = false">Close</el-button>\n' +
        '    </span>\n' +
        '    </el-dialog>\n' +
        '  </div>',
    components: {},
    data() {
        return {
            apiAudit: false,
            currentPage: 1,
            pageSize: 8,
            logTotal: 0,
            apiAuditRecode: [],
            auditLog: false,
            details: false,
            node_detail: "",
            icons: [
                {
                    success: "el-icon-position success",
                    error: "el-icon-circle-close error",
                    info: 'el-icon-position success',
                    line_info: 'success-line',
                    dis: true
                }, {
                    success: "el-icon-location-outline success",
                    error: "el-icon-circle-close error",
                    info: '',
                    line_info: '',
                    dis: false
                }, {
                    success: "el-icon-location-outline success",
                    error: "el-icon-circle-close error",
                    info: '',
                    line_info: '',
                    dis: false
                }, {
                    success: "el-icon-monitor success",
                    error: "el-icon-monitor error",
                    warning: "warning-line warning",
                    info: '',
                    line_info: '',
                    dis: true
                }, {
                    success: "el-icon-location-outline success",
                    error: "el-icon-circle-close error",
                    info: '',
                    line_info: '',
                    dis: false
                }
            ],
            line_icon: {success: "success-line", error: "error-line"},
            entry_node: true,
            routing_node: false,
            authorize_node: false,
            end_node: false,
            limiting_node: false,
            processField: [["处理时间：3ms", "响应结果：success"], ["处理时间：3ms", "响应结果：success"],
                ["处理时间：3ms", "响应结果：success"], ["处理时间：3ms", "响应结果：success"]]
        };
    },
    methods: {
        async show(i) {
            this.$loading()
            this.processField[0] = ["请求时间：" + i.requestTime, "源IP：" + i.sourceAddr, "用户标识：" + i.useragent]
            await axios.get("https://nieva.cn/core/query/ip?ip=" + i.sourceAddr).then(res => {
                if (res.data.code === "Success") {
                    let addr = res.data.data.prov !== null ? res.data.data.prov : res.data.data.country
                    let city = res.data.data.city !== "" ? "-" : "";
                    this.processField[0] = this.processField[0].concat(["请求位置：" + addr + city + res.data.data.city, "ISP：" + res.data.data.isp, "来源：" + res.data.data.source])
                }
            }).catch(e => {
                console.debug(e)
            })
            setTimeout(() => {
                this.auditLog = true
                let processNode = JSON.parse(i.recodeDetail);
                if (processNode.authorizeNode !== null && processNode.authorizeNode !== undefined) {
                    let appName = processNode.authorizeNode.appName !== undefined ? processNode.authorizeNode.appName : "无";
                    this.processField[1] = ["鉴权结果：" + processNode.authorizeNode.result, "ApplicationName：" + appName, "消耗时间：" + processNode.authorizeNode.timeConsuming + "ms"]
                    this.icons[1].info = processNode.authorizeNode.code === 200 ? this.icons[1].success : this.icons[1].error
                    this.icons[1].line_info = processNode.authorizeNode.code === 200 ? this.line_icon.success : this.line_icon.error
                    this.icons[1].dis = true
                } else {
                    this.icons[1].dis = false
                }
                if (processNode.routingNode !== null && processNode.routingNode !== undefined) {
                    this.processField[2] = ["请求路径：" + processNode.routingNode.fullUrl, "消耗时间：" + processNode.routingNode.timeConsuming + "ms"
                        , "查询参数：" + processNode.routingNode.requestParam, "JSON参数：" + processNode.routingNode.requestBody, "请求头：" + processNode.routingNode.requestHeader
                        , "响应结果：" + processNode.routingNode.responseBody, "执行结果：" + processNode.routingNode.result]
                    this.icons[2].info = processNode.routingNode.code === 200 ? this.icons[2].success : this.icons[2].error
                    this.icons[2].line_info = processNode.routingNode.code === 200 ? this.line_icon.success : this.line_icon.error
                    this.icons[2].dis = true
                } else {
                    this.icons[2].dis = false
                }
                if (processNode.limitingNode !== null && processNode.limitingNode !== undefined) {
                    let result = processNode.limitingNode.result !== undefined ? processNode.limitingNode.result : "执行成功"
                    this.processField[4] = ["消耗时间：" + processNode.limitingNode.timeConsuming + "ms", "执行结果：" + result]
                    this.icons[4].info = processNode.limitingNode.code === 200 ? this.icons[4].success : this.icons[4].error
                    this.icons[4].line_info = processNode.limitingNode.code === 200 ? this.line_icon.success : this.line_icon.error
                    this.icons[4].dis = true
                } else {
                    this.icons[4].dis = false
                }
                let err = i.errMsg === null || i.errMsg === undefined || i.errMsg === '' ? '无' : i.errMsg
                this.processField[3] = ["流程结束时间：" + i.responseTime, "错误信息：" + err]
                this.icons[3].info = i.status === "正常" ? this.icons[3].success : this.icons[3].error
                this.icons[3].dis = true
                this.$loading().close()
            }, 1);
        },
        formatDate(data) {
            if (data == null)
                return null;
            const dt = new Date(data);
            const localDt = new Date(dt.getTime() + (8 * 60 + dt.getTimezoneOffset()) * 60 * 1000); // 加上时差并转换为北京时间
            const year = localDt.getFullYear();
            const month = String(localDt.getMonth() + 1).padStart(2, '0');
            const day = String(localDt.getDate()).padStart(2, '0');
            const hours = String(localDt.getHours()).padStart(2, '0');
            const minutes = String(localDt.getMinutes()).padStart(2, '0');
            const seconds = String(localDt.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        filterTag(value, row) {
            return row.status === value;
        },
        handleCurrentChange(currentPage) {
            console.log(currentPage)
            this.getAudit(this.apiAuditRecode[0].idApi, currentPage)
        },
        getAudit(idApi, currentPage) {
            let current = 1;
            if (currentPage !== undefined) {
                current = currentPage
            }
            this.$loading()
            axios.get(window.RT_ENV.host_config.host + "/api/audit/log?size=8&current=" + current + "&idApi=" + idApi, {headers: {"token": sessionStorage.getItem("current-authorized")}}).then(res => {
                if (res.data.code === 200) {
                    this.apiAuditRecode = res.data.data.records
                    this.logTotal = res.data.data.total
                    this.pageSize = res.data.data.size
                    this.apiAuditRecode.forEach(item => {
                        item.requestTime = this.formatDate(item.requestTime)
                        item.responseTime = this.formatDate(item.responseTime)
                        if (item.status === 200)
                            item.status = "正常"
                        else
                            item.status = "异常"
                    })
                    this.$notify.info({
                        title: '操作提示',
                        message: '单击项目的状态可查看详细日志'
                    });
                    this.apiAudit = true
                    this.$loading().close()
                } else {
                    this.$message.warning(res.data.message)
                    this.$loading().close()
                }
            }).catch(e => {
                console.debug(e)
                this.$message.warning("获取失败")
                this.$loading().close()
            })
        },
        detailNode(i) {
            this.entry_node = false
            this.authorize_node = false
            this.routing_node = false
            this.end_node = false
            this.limiting_node = false
            if (i === 0) {
                this.entry_node = true
            }
            if (i === 1) {
                this.authorize_node = true
            }
            if (i === 2) {
                this.routing_node = true
            }
            if (i === 3) {
                this.end_node = true
            }
            if (i === 4) {
                this.limiting_node = true
            }
        },
        out() {
            this.auditLog = false
        },
        showDetail(i) {
            this.details = true
            this.node_detail = i;
        }
    },
    mounted() {

    },
    watch: {
        auditLog() {
            this.entry_node = true
            this.authorize_node = false
            this.routing_node = false
            this.end_node = false
            this.limiting_node = false
        }
    }
})